//
//  PopView.swift
//  SinaWeibo
//
//  Created by 郭平 on 15/10/11.
//  Copyright © 2015年 郭平. All rights reserved.
//

import UIKit

protocol popViewDelegate: NSObjectProtocol {

     func popViewWillDismiss()
}

class PopView: UIButton {

     weak var delegate: popViewDelegate?
     var imageBack: UIImageView?
    
    init(customView: UIView){
        
        super.init(frame: CGRectMake(0, 0, SCREENW, SCREENH))
        
        addTarget(self, action: "converButtonClick", forControlEvents: .TouchUpInside)
        
        // 初始化控件
        setupView(customView)
        
      self.backgroundColor = UIColor(white: 0, alpha: 0.1)
     }
    
    @objc func converButtonClick(){
    
        dismiss()
    }
    func dismiss(){
        //得在消失的时候让外界知道,我消失了
        
        if let d = self.delegate {
            //告诉外界,我消失了
            d.popViewWillDismiss()
        }
        
        //从父控件移除
        removeFromSuperview()
    }
    
    private func setupView(customView: UIView){
       
        let image = UIImage(named: "popover_background")
        let imageBack = UIImageView(image:image?.stretchableImageWithLeftCapWidth(Int(image!.size.width * 0.5), topCapHeight: Int(image!.size.height * 0.5)))
        
        imageBack.userInteractionEnabled = true
        imageBack.size = CGSizeMake(customView.width + 10, customView.height + 22)
        
        self.addSubview(imageBack)
        self.imageBack = imageBack

        customView.x = 5
        customView.y = 13
        imageBack.addSubview(customView)
        
    }
    
    func show(targetButton: UIButton){
        
        let rect = targetButton.superview!.convertRect(targetButton.frame, toView: nil)
        
        printLog(rect)
        
        self.imageBack?.centerX = targetButton.centerX
        self.imageBack?.y = CGRectGetMaxY(rect)
        
        //取出window
        let window = UIApplication.sharedApplication().windows.last
        //添加button
        window?.addSubview(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
